package com.my.socket.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.oio.OioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.oio.OioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by ZhongGang
 * at 2017/6/28 11:34
 */
public class EchoServer {
    private static final Logger LOGGER = LoggerFactory.getLogger(EchoServer.class);

    private int port;

    public EchoServer(int port) {
        this.port = port;
    }

    public static void main(String[] args) throws Exception {
        EchoServer echoServer = new EchoServer(9999);
        echoServer.start();
    }

    public void start() throws Exception {
        ServerBootstrap server = new ServerBootstrap();
        server.group(new NioEventLoopGroup());
        server.channel(NioServerSocketChannel.class);

//        server.group(new OioEventLoopGroup());
//        server.channel(OioServerSocketChannel.class);

        server.localAddress("127.0.0.1", this.port);
        server.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                ChannelPipeline pipeline = ch.pipeline();
//                pipeline.addLast(new StringEncoder());
//                pipeline.addLast(new StringDecoder());
                pipeline.addLast(new StringCodec());
                pipeline.addLast(new EchoServerHandler());
            }
        });

        ChannelFuture future = server.bind().sync();
        LOGGER.info("server started at the port {}", this.port);
        future.channel().closeFuture().sync();
    }
}
